import QrCode from 'qrcode-js';

//创建GUID
export function createGuid() {
    let str = new Date().getTime().toString(16);
    do {
        str += Math.random().toString(16).replace('0.', '');
    } while (str.length < 32);
    return str.substring(0, 8) + '-' + str.substring(8, 12) + '-' + str.substring(12, 16) + '-' + str.substring(16, 20) + '-' + str.substring(20, 32);
}

export const guidEmpty = "00000000-0000-0000-0000-000000000000";

// 字符串去掉空格
export function trim(str) {
    return (str === undefined || str === null) ? "" : str.replace(/(^\s*)|(\s*$)/g, "").replace(new RegExp("(^　*)|(　*$)", "g"), "");
}

// 字符串是否为空
export function isNullOrEmpty(value) {
    return (value === null || value === undefined) || trim(value.toString()) === "";
}

// 字符串是否为空，如果为空只返回默认值，反之返回当前值
export function isNullOrEmptyReturnDefault(value, defaultValue) {
    return isNullOrEmpty(value) ? defaultValue : value;
}

// 获取查询字符串
export function getQueryString(query) {
    const args = {};
    const { location } = window;
    query = query || location.search.substring(1);
    const index = query.indexOf("?");
    if (index > 0) query = query.substring(index + 1);

    const pairs = query.split("&");
    for (let i = 0; i < pairs.length; i++) {
        const pos = pairs[i].indexOf('=');
        if (pos === -1) continue;
        const argname = pairs[i].substring(0, pos);
        const value = pairs[i].substring(pos + 1);
        args[argname] = decodeURIComponent(value);
    }
    return args;
}

export function addUrlRandom(url) {
    if (isNullOrEmpty(url)) return "";

    const rc = getRandomChars();
    const rd = Math.random();
    url += url.indexOf("?") >= 0 ? "&" : "?";
    url += `_r${rc}=${rd}`;
    return url;
}

export function addUrlParams(url, name, value) {
    if (isNullOrEmpty(url)) return "";
    if (value === undefined || value === null) return url;
    url += url.indexOf("?") >= 0 ? "&" : "?";
    value = encodeURIComponent(value);
    url += `${name}=${value}`;
    return url;
}

export function addUrlObjParams(url, obj) {
    if (isNullOrEmpty(url)) return "";
    if (!obj) return url;

    const qs = toQueryString(obj);
    if (qs) url += (url.indexOf("?") >= 0 ? "&" : "?") + qs;
    return url;
}

export function getRandomChars(len) {
    len = len || 10;
    const chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz";
    const str = [];
    for (let i = 0; i < len; i++) {
        str.push(chars.charAt(Math.floor(Math.random() * chars.length)));
    }
    return str.join("");
}

// 是否数组
export function isArray(obj) {
    if (obj === null || obj === undefined) return false;
    return typeof (obj) === "object" && obj.length >= 0;
}

export function isFunction(obj) {
    return typeof obj === "function" && typeof obj.nodeType !== "number";
}

export function isEmptyArray(obj) {
    if (!isArray(obj) || obj.length === 0) return true;
    return false;
}

export function isNoEmptyArray(obj) {
    if (isArray(obj) && obj.length > 0) return true;
    return false;
}

export function isObject(obj) {
    if (obj === null || obj === undefined) return false;
    return typeof (obj) === "object" && Object.prototype.toString.call(obj).toLowerCase() === "[object object]" && !obj.length;
}

export function getObjValue(obj, name, defaultValue) {
    if (!isObject(obj) || isNullOrEmpty(name)) return defaultValue;

    for (const key in obj) if (key.toLowerCase() === name.toLowerCase()) return obj[key];

    return defaultValue;
}

export function getRootPath(blPath) {
    if (blPath) {
        const names = window.location.pathname.substr(1).split("/");
        let path = "";
        if (names.length > 1) {
            names.splice(names.length - 1, 1);
            path = `/${names.join("/")}/`;
        }

        return `${window.location.protocol}//${window.location.host}${path}`;
    }
    return `${window.location.protocol}//${window.location.host}/`;
}

export function isEmptyObject(obj) {
    if (!isObject(obj)) return true;

    if (Object.getOwnPropertyNames(obj).length > 0) return false;

    let blEmpty = true;
    for (const key in obj) if (key) { blEmpty = false; break; }

    return blEmpty;
}

export function copy(a, b, c) {
    if (!isObject(a) || !isObject(b)) return;

    if (isArray(c)) {
        let n = "";
        for (let i = 0; i < c.length; i++) {
            n = c[i];
            if (b[n] !== undefined) a[n] = b[n];
            else for (const k in b) if (k === n) { a[n] = b[n]; break; }
        }
    }
    else for (const k in b) a[k] = b[k];
}

export function isEquals(a, b, c) {
    if (a === undefined && b === undefined) return true;
    if (a === null && b === null) return true;
    if (a === b) return true;

    const a_isArray = isArray(a);
    const b_isArray = isArray(b);
    const a_isObj = isObject(a);
    const b_Obj = isObject(b);

    if ((a_isArray && !b_isArray) || (!a_isArray && b_isArray)) return false;
    if ((a_isObj && !b_Obj) || (!a_isObj && b_Obj)) return false;

    if (a_isArray && b_isArray) return isArrayEquals(a, b);
    if (a_isObj && b_Obj) return isObjectEquals(a, b);

    const sa = isNullOrEmpty(a) ? "" : a.toString();
    const sb = isNullOrEmpty(b) ? "" : b.toString();
    return c ? sa.toLowerCase() === sb.toLowerCase() : sa === sb;
}

export function isArrayEquals(a, b) {
    if (a === b) return true;
    if (a.length !== b.length) return false;

    let blEquals = true;
    for (let i = 0; i < a.length; i++) {
        blEquals = isObjectEquals(a[i], b[i]);
        if (!blEquals) break;
    }

    return blEquals;
}

export function isObjectEquals(a, b) {
    if (a === b) return true;

    let blEquals = true;

    for (const k in a) {
        blEquals = isEquals(a[k], b[k]);
        if (!blEquals) break;
    }

    if (blEquals) {
        for (const k in b) {
            if (a[k] === undefined) {
                blEquals = false;
                break;
            }
        }
    }

    return blEquals;
}

export function arrayFirst(list, fn) {
    if (!isArray(list)) return null;
    const list2 = list.filter(fn);
    return list2.length > 0 ? list2[0] : null;
}

export function setStorage(key, value, time) {
    try {
        time = time || 0;
        window.localStorage.setItem(key, value);

        if (time > 0) {
            key += "_Time";
            const tv = `${(new Date().getTime() + time * 60 * 1000).toString()}_${time.toString()}`;
            window.localStorage.setItem(key, tv);
        }
    }
    catch (ex) {
        console.warn("utils-common/Common", ex);
    }
}

export function getStorage(key) {
    let value = "";
    try {
        value = window.localStorage.getItem(key);
        const tkey = `${key}_Time`;
        const tvs = window.localStorage.getItem(tkey);
        if (!isNullOrEmpty(tvs)) {
            const vs = tvs.split("_");
            let tv = parseFloat(vs[0]);
            const time = parseFloat(vs[1]);
            if (tv > 0) {
                const ct = new Date().getTime();
                if (ct > tv) {
                    value = "";
                    window.localStorage.removeItem(key);
                    window.localStorage.removeItem(tkey);
                }
                else {
                    tv = `${(new Date().getTime() + time * 60 * 1000).toString()}_${time.toString()}`;
                    window.localStorage.setItem(tkey, tv);
                }
            }
        }
    }
    catch (ex) {
        console.warn("utils-common/common", ex);
    }
    return isNullOrEmpty(value) ? "" : value;
}

export function removeStorage(key) {
    try {
        window.localStorage.removeItem(key);
    }
    catch (ex) {
        console.warn("utils-common/common", ex);
    }
}

export function getNumber(value, scale) {
    const f = parseFloat(value);
    if (isNaN(f)) return 0;
    if (f === 0) return f;

    scale = (scale || 2);
    scale = 10 ** scale;
    return Math.round(f * scale) / scale;
}

export function toCurrency(value, blFixed2) {
    blFixed2 = blFixed2 === undefined ? true : blFixed2;
    const floatValue = parseFloat(value);
    if (isNaN(floatValue)) {
        return value;
    }

    let flString = blFixed2 ? floatValue.toFixed(2) : floatValue.toString();
    const r = /(\d+)(\d{3})/;
    while (r.test(flString)) {
        flString = flString.replace(r, "$1,$2");
    }
    return flString;
}

export function addComma(value) {
    if (!value || isNaN(value)) return value;
    const vs = value.toString().split('.');
    let value1 = vs[0];
    const value2 = vs.length > 1 ? `.${vs[1]}` : '';
    const r = /(\d+)(\d{3})/;
    while (r.test(value1)) {
        value1 = value1.replace(r, "$1,$2");
    }
    return value1 + value2;
}

export function toFixed(value, num) {
    if (!value) return value;
    return getNumber(value).toFixed(num);
}

export function getDateString(myDate, isDate) {
    if (isNullOrEmpty(myDate)) return "";
    if (typeof (myDate) === "number") myDate = new Date(myDate);

    const year = myDate.getFullYear().toString();
    let month = (myDate.getMonth() + 1);
    month = month < 10 ? `0${month.toString()}` : month.toString();
    let day = myDate.getDate();
    day = day < 10 ? `0${day.toString()}` : day.toString();
    if (isDate) {
        return `${year}-${month}-${day}`;
    }

    let hh = myDate.getHours();
    hh = hh < 10 ? `0${hh.toString()}` : hh.toString();
    let mm = myDate.getMinutes();
    mm = mm < 10 ? `0${mm.toString()}` : mm.toString();
    let ss = myDate.getSeconds();
    ss = ss < 10 ? `0${ss.toString()}` : ss.toString();
    return `${year}-${month}-${day} ${hh}:${mm}:${ss}`;
}

export function toDateMilliSeonds(dateString) {
    let ms = Date.parse(dateString);
    if (ms > 0) return ms;

    ms = Date.parse(dateString.replace("-", "/"));
    if (ms > 0) return ms;

    const d = convertToDate(dateString, "yyyy-MM-dd HH:mm:ss");
    return d.getTime();
}

export function convertToDate(dateString, format) {
    if (isNullOrEmpty(dateString)) return null;
    if (typeof (dateString) === "number") return new Date(dateString);
    if (typeof dateString !== "string") return dateString;

    if (!format) {
        let ms = Date.parse(dateString);
        if (ms > 0) return new Date(ms);

        ms = Date.parse(dateString.replace("-", "/"));
        if (ms > 0) return new Date(ms);

        format = "yyyy-MM-dd HH:mm:ss";
    }

    let year, month, day, hh, mm, ss, timeFormat, time;
    if (format.substring(0, 10) === "yyyy-MM-dd" || format.substring(0, 10) === "yyyy/MM/dd") {
        year = dateString.substring(0, 4);
        month = dateString.substring(5, 7);
        day = dateString.substring(8, 10);
        if (format.length > 10) timeFormat = trim(format.substring(10, format.length));
        if (format.length > 10) time = trim(dateString.substring(10, dateString.length));
    }
    if (format.substring(0, 10) === "MM-dd-yyyy" || format.substring(0, 10) === "MM/dd/yyyy") {
        year = dateString.substring(6, 10);
        month = dateString.substring(0, 2);
        day = dateString.substring(3, 5);
        if (format.length > 10) timeFormat = trim(format.substring(10, format.length));
        if (format.length > 10) time = trim(dateString.substring(10, dateString.length));
    }
    if (format.substring(0, 8) === "yyyyMMdd") {
        year = dateString.substring(0, 4);
        month = dateString.substring(4, 6);
        day = dateString.substring(6, 8);
        if (format.length > 8) timeFormat = trim(format.substring(8, format.length));
        if (format.length > 8) time = trim(dateString.substring(8, dateString.length));
    }
    if (format.substring(0, 8) === "MMddyyyy") {
        year = dateString.substring(4, 8);
        month = dateString.substring(0, 2);
        day = dateString.substring(2, 4);
        if (format.length > 8) timeFormat = trim(format.substring(8, format.length));
        if (format.length > 8) time = trim(dateString.substring(8, dateString.length));
    }
    if (!isNullOrEmpty(time) && !isNullOrEmpty(timeFormat)) {
        if (!isNullOrEmpty(timeFormat) && timeFormat === "HH:mm:ss") {
            hh = time.substring(0, 2);
            mm = time.substring(3, 5);
            ss = time.substring(6, 8);
        }
        else if (!isNullOrEmpty(timeFormat) && timeFormat === "HHmmss") {
            hh = time.substring(0, 2);
            mm = time.substring(2, 4);
            ss = time.substring(4, 6);
        }
    }

    year = getIntValue(year);
    month = getIntValue(month) - 1;
    day = getIntValue(day);

    if (!isNullOrEmpty(time) && !isNullOrEmpty(timeFormat)) {
        hh = getIntValue(hh);
        mm = getIntValue(mm);
        ss = getIntValue(ss);

        return new Date(year, month, day, hh, mm, ss);
    }
    return new Date(year, month, day);
}

export function getCurrentDate() {
    const myDate = new Date();
    return getDateString(myDate);
}

export function jsonParse(str) {
    if (isNullOrEmpty(str)) return null;

    return JSON.parse(str);
}

export function arrayMax(list, name) {
    if (list.length === 0) return null;
    list = list.sort((a, b) => a[name] > b[name] ? -1 : 1);
    return list[0];
}

export function getFloatValue(value) {
    if (typeof (value) === "number") return value;
    const f = parseFloat(value);
    return isNaN(f) ? 0 : f;
}

export function getIntValue(value) {
    const i = parseInt(value, 10);
    return isNaN(i) ? 0 : i;
}

export function dateFormat(date, format) {
    if (!date) return date;
    if (typeof (date) === "number") date = getDateString(new Date(date));
    if (format === "yyyy/MM/dd" || format === "yyyy-MM-dd") {
        const s = date.toString().substr(0, 10);
        const st = format === "yyyy/MM/dd" ? "/" : "-";
        return s.substr(0, 4) + st + s.substr(5, 2) + st + s.substr(8, 2);
    }
    return date;
}

export function getStyle(style) {
    if (!style) return style;
    if (style.inputTypeDataId) delete style.inputTypeDataId;
    if (style.backgroundImage && style.backgroundImage.indexOf('url(') !== 0) style.backgroundImage = `url(${style.backgroundImage})`;

    return style;
};

export function getYesterdayDate() {
    const date = new Date();
    date.setTime(date.getTime() - 24 * 60 * 60 * 1000);
    return getDateString(date);
}

export function getTomorrowDate() {
    const date = new Date();
    date.setTime(date.getTime() + 24 * 60 * 60 * 1000);
    return getDateString(date);
}

export function getWeek(date) {
    date = date || new Date();
    const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    return days[date.getDay()];
}

export function addDays(date, days) {
    return new Date(date.getTime() + 24 * 60 * 60 * 1000 * days);
}

export function getCookie(name) {
    const reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`);
    const arr = document.cookie.match(reg);
    if (arr) return decodeURIComponent(arr[2]);
    return null;
}

export function setCookie(name, value, days, path) {
    days = days || 1;
    path = path || "/";
    const exp = new Date();
    exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
    document.cookie = `${name}=${encodeURIComponent(value)}; expires=${exp.toGMTString()}; path=${path}`;
}

export function removeCookie(name, path) {
    setCookie(name, "", -1, path);
}

export function numbertoTime(surplus) {
    if (!surplus) return surplus;

    let surplusHour = parseInt((surplus / 1000) / 60 / 60, 10);// 剩余小时
    let surplusMinute = parseInt((surplus % (1000 * 60 * 60)) / (1000 * 60), 10);// 剩余分
    let surplusSecond = parseInt((surplus % (1000 * 60)) / 1000, 10);// 剩余秒
    if (surplusHour < 10) surplusHour = `0${surplusHour}`;
    if (surplusMinute < 10) surplusMinute = `0${surplusMinute}`;
    if (surplusSecond < 10) surplusSecond = `0${surplusSecond}`;
    return `${surplusHour}:${surplusMinute}:${surplusSecond}`;
}

// 判断输入文本框是否是输入两位小数的浮点数
export function isDecimal2(value) {
    const reg = new RegExp("^-?\\d+$|^(-?\\d+)(\\.\\d{1})?$|^(-?\\d+)(\\.\\d{2})?$");
    return reg.test(value);
}

export function toQueryString(obj) {
    const list = [];
    let v = null;
    for (const key in obj) { v = encodeURIComponent(obj[key]); list.push(`${key}=${v}`); }
    return list.join("&");
}

export function isWeiXin() {
    return !!window.navigator.userAgent.match(/MicroMessenger/i);
}

export function isH5() {
    const ua = navigator.userAgent;
    if ((ua.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) return true;

    const bisIpad = !!ua.match(/ipad/i);
    const bisIphoneOs = !!ua.match(/iphone os/i);
    const bisMidp = !!ua.match(/midp/i);
    const bisUc = !!ua.match(/ucweb/i);
    const bisAndroid = !!ua.match(/android/i);
    const bisCE = !!ua.match(/windows ce/i);
    const bisWM = !!ua.match(/windows mobile/i);

    if (bisIpad || bisIphoneOs || bisMidp || bisUc || bisAndroid || bisCE || bisWM) return true;

    if (ua.match(/AppleWebKit.*Mobile.*/)) return true;

    return false;
}

export function isAndroid() {
    const ua = navigator.userAgent;
    return !!ua.match(/android/i);
}

export function isIos() {
    const ua = navigator.userAgent;
    if ((ua.match(/(iPhone|iPod|ios|iPad)/i))) return true;

    const bisIpad = !!ua.match(/ipad/i);
    const bisIphoneOs = !!ua.match(/iphone os/i);

    if (bisIpad || bisIphoneOs) return true;

    return false;
}

export function setDefaultValue(obj, name, value) {
    if (obj[name] === undefined) obj[name] = value;
}

export function listForEach(list, fn) {
    for (let i = 0; i < list.length; i++) {
        if (fn(list[i], i) === false) {
            break;
        }
    }
}

// 不四舍五入直接截断
export function toCurrencyNo45(num) {
    num = getFloatValue(num).toFixed(3);
    return num.substring(0, num.lastIndexOf('.') + 3).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
}

export function replaceDataContent(data, content, isUrl, startTag, endTag) {
    if (!content || !data) return content;

    startTag = startTag || '#{';
    endTag = endTag || '}';

    if (content.indexOf(startTag) < 0) return content;
    let keyValue = ""; let v = null;
    for (const key in data) {
        keyValue = startTag + key + endTag;
        v = data[key];
        v = isNullOrEmpty(v) ? "" : v.toString();

        if (isUrl) v = encodeURIComponent(v);

        content = content.replace(new RegExp(keyValue, "g"), v);
        if (content.indexOf(startTag) < 0) break;
    }
    return content;
}

export function assign(a, b, c) {
    if (!isObject(a)) return a;

    const objList = [];
    if (isObject(b)) for (const k in b) a[k] = clone(b[k], objList);

    if (isObject(c)) for (const k in c) a[k] = clone(c[k], objList);

    return a;
}

export function arrayClone(a, objList) {
    if (!isArray(a)) return a;

    const dataList = [];
    for (let i = 0; i < a.length; i++) {
        dataList.push(clone(a[i], objList));
    }
    return dataList;
}

export function clone(a, objList) {
    objList = objList === undefined ? [] : objList;
    if (isArray(a)) return arrayClone(a, objList);

    if (!isObject(a)) return a;

    let blExists = false;
    for (let i = 0; i < objList.length; i++) {
        if (objList[i] === a) {
            blExists = true;
            break;
        }
    }

    if (blExists) return a;

    objList.push(a);

    const c = {};

    for (const key in a) {
        if (isArray(a[key])) {
            c[key] = arrayClone(a[key], objList);
        }
        else if (isObject(a[key])) {
            c[key] = clone(a[key], objList);
        }
        else {
            c[key] = a[key];
        }
    }

    return c;
}

export function inherit(obj1, obj2) {
    if (!isObject(obj1) || !isObject(obj2)) return;

    for (const key in obj2) if (obj1[key] === undefined) obj1[key] = obj2[key];
}

export function isAdmin() {
    const { pathname } = window.location;
    return pathname.toLowerCase().indexOf("/admin") === 0;
}

export function getImageUrl(name) {
    return require(`../assets/${name}`);
}

export function remvoeHtmlTag(html) {
    if (isNullOrEmpty(html)) return html;

    html = html.replace(/<[^>]+>/g, "");
    html = html.replace(/&nbsp;/ig, "");
    html = html.replace(/&middot;/ig, "");
    html = html.replace(/&mdash;/ig, "");
    html = html.replace(/&bull;/g, "");
    html = html.replace(/&#(\d+);/g, "");
    html = html.replace(/&lt;/g, "<");
    html = html.replace(/&gt;/g, ">");
    html = html.replace(/([\r\n])[\s]+/g, "");

    html = trim(html);

    return html;
}

export function postFormData(url, formData, headers, successCallback, errorCallback, async) {
    let xmlHttp = null;

    // 创建请求
    xmlHttp = createRequest();

    // 打开请求
    xmlHttp.open('POST', addUrlRandom(url), async);

    if (headers) {
        for (const key in headers) {
            xmlHttp.setRequestHeader(key, headers[key]);
        }
    }

    // 处理请求响应返回
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState === 4) {
            if (xmlHttp.status === 200) {
                successCallback && successCallback(JSON.parse(xmlHttp.responseText));
            }
            else {
                const msg = xmlHttp.statusText ? `${xmlHttp.status}:${xmlHttp.statusText}` : xmlHttp.responseText;
                errorCallback && errorCallback(msg);
            }
        }
    };

    // 发送请求
    xmlHttp.send(formData);

    // 创建请求对象
    function createRequest() {
        return new XMLHttpRequest();
    };

    return xmlHttp;
}

export function getFileExt(fileName) {
    if (isNullOrEmpty(fileName)) return '';
    const ns = fileName.split('.');
    if (ns.length < 2) return '';
    return ns.pop().toLowerCase();
}

export function getImageFileWidthHeight(file) {
    return new Promise((resolve, reject) => {
        try {
            const reader = new FileReader();
            reader.onload = function (e) {
                const data = e.target.result;
                const image = new Image();
                image.onload = function () {
                    const { width } = image;
                    const { height } = image;
                    resolve({ width, height });
                };
                image.src = data;
            };
            reader.readAsDataURL(file);
        }
        catch (err) {
            reject(err);
        }
    });
}

export function compressImage(file, width, height, type, quality, maxWidth, maxHeight) {
    return new Promise((resolve, reject) => {
        try {
            const ready = new FileReader();
            ready.readAsDataURL(file);
            ready.onload = function () {
                getImage(this.result).then(res => {
                    resolve(canvasDataURL(res, width, height, type, quality, maxWidth, maxHeight));
                });
            };
        } catch (err) { reject(err); }
    });
}

export function getImage(src) {
    return new Promise((resolve, reject) => {
        try {
            const img = new Image();
            img.src = src;
            img.onload = function () {
                resolve(img);
            };
            img.onerror = function (err) {
                reject(err);
            };
        }
        catch (err) { reject(err); }
    });
}

export function canvasDataURL(img, width, height, type, quality, maxWidth, maxHeight) {
    width = width || img.width;
    height = height || img.height;
    type = type || 'image/jpeg';
    quality = quality || 0.5;
    maxWidth = maxWidth || 1920;
    maxHeight = maxHeight || 1080;

    if (width > maxWidth) {
        height = maxWidth * height / width;
        width = maxWidth;
    }
    if (height > maxHeight) {
        width = maxHeight * width / height;
        height = maxHeight;
    }

    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);
    return canvas.toDataURL(type, quality);
}

export function dataURItoBlob(base64Data) {
    let byteString;
    if (base64Data.split(',')[0].indexOf('base64') >= 0) { byteString = atob(base64Data.split(',')[1]); }// base64 解码
    else {
        byteString = unescape(base64Data.split(',')[1]);
    }
    const mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];// mime类型 -- image/png

    const ia = new Uint8Array(byteString.length);// 创建视图
    for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([ia], {
        type: mimeString
    });
    return blob;
}

export function blobToDataURI(blob) {
    return new Promise((resolve, reject) => {
        try {
            const reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onload = function (e) {
                resolve(e.target.result);
            };
        }
        catch (err) { reject(err); }
    });
}

export function mov2mp4(file) {
    return new Promise((resolve, reject) => {
        try {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                const mine = 'video/mp4';
                const fileName = file.name.replace(/.mov/i, '.mp4');

                resolve(dataURLtoFile(e.target.result, fileName, mine));
            };
        }
        catch (err) { reject(err); }
    });
}

export function captureImage(video, scale, type, quality) {
    const canvas = document.createElement('canvas');
    scale = scale || 1;
    type = type || 'image/jpeg';
    quality = quality || 0.5;
    canvas.width = video.videoWidth * scale;
    canvas.height = video.videoHeight * scale;
    canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
    return canvas.toDataURL(type, quality);
}

// 将base64转换为文件
export function dataURLtoFile(dataUrl, filename, mine) {
    const arr = dataUrl.split(','); const mime = mine || arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]); let n = bstr.length; const u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
}

export function removeQueryParams(url, name) {
    let key = `&${name}=`;
    let index = url.indexOf(key);
    if (index > 0) {
        const end = url.indexOf("&", index + key.length);
        if (end > 0) return url.substring(0, index) + url.substring(end);
        return url.substring(0, index);
    }

    key = `?${name}=`;
    index = url.indexOf(key);
    if (index > 0) {
        const end = url.indexOf("&", index + key.length);
        if (end > 0) return `${url.substring(0, index)}?${url.substring(end + 1)}`;
        return url.substring(0, index);
    }

    return url;
}

export function toRem(px) {
    if (px === 0) return 0;
    return `${(px / 32).toFixed(4)}rem`;
}

export function getRequest(url, headers, successCallback, async) {
    const xmlHttp = createRequest();

    url = addUrlRandom(url);

    // 打开请求
    xmlHttp.open('Get', url, async);

    if (headers) {
        for (const key in headers) {
            xmlHttp.setRequestHeader(key, headers[key]);
        }
    }

    // 处理请求响应返回
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState === 4) {
            if (xmlHttp.status === 200) {
                successCallback && successCallback(JSON.parse(xmlHttp.responseText));
            }
        }
    };

    // 发送请求
    xmlHttp.send();

    // 创建请求对象
    function createRequest() {
        if (window.XMLHttpRequest) return new XMLHttpRequest();
        if (window.ActiveXObject) return new window.ActiveXObject("Microsoft.XMLHTTP");
    };

    return xmlHttp;
};

export function RemoveHttps(url) {
    return url.replace(/^https:/i, '').replace(/^http:/i, '');
}

export function setVideoPlay(video, callback) {
    const getNetworkType = () => {
        window.WeixinJSBridge && window.WeixinJSBridge.invoke('getNetworkType', {}, (e) => {
            video.play();
            callback && callback();
        }, false);
    };

    if (window.WeixinJSBridge) getNetworkType();
    else {
        document.addEventListener("WeixinJSBridgeReady", function () {
            getNetworkType();
        }, false);
    }
}

export function getNetworkType(callback) {
    const getNetworkType = () => {
        window.WeixinJSBridge && window.WeixinJSBridge.invoke('getNetworkType', {}, (e) => {
            callback && callback();
        }, false);
    };

    if (window.WeixinJSBridge) getNetworkType();
    else {
        document.addEventListener("WeixinJSBridgeReady", function () {
            getNetworkType();
        }, false);
    }
}

export function loadScript(id, url, callback) {
    const ele = document.getElementById(id);
    if (ele) {
        callback && callback();
        return;
    }
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.id = id;
    script.onload = function () { callback && callback(); };
    script.src = url;
    document.body.appendChild(script);
}

export function arrayRemove(list, item, key) {
    let index = -1;
    for (let i = 0; i < list.length; i++) {
        if (list[i][key] === item[key]) {
            index = i;
            break;
        }
    }
    if (index > -1) list.splice(index, 1);
}

export function secondsToTimeText(seconds) {
    if (seconds < 1) return '';
    const ds = 24 * 60 * 60;
    const hs = 60 * 60;
    const ms = 60;

    const dnum = parseInt(seconds / ds);
    const hnum = parseInt((seconds - dnum * ds) / hs);
    const mnum = parseInt((seconds - dnum * ds - hnum * hs) / ms);
    const snum = seconds - dnum * ds - hnum * hs - mnum * ms;

    const dnums = dnum > 0 ? `${dnum}天` : '';
    const hnums = hnum > 0 ? `${hnum}小时` : '';
    const mnums = mnum > 0 ? `${mnum}分钟` : '';

    return dnums + hnums + mnums + snum + '秒';
}

export function setElementVisible(ele, visible) {
    if (visible) {
        if (ele.style.display === 'none') ele.style.display = ele.display || '';
    }
    else {
        if (ele.style.display !== 'none') ele.display = ele.style.display;
        ele.style.display = 'none';
    }
}

export function addHttps(url, ishttp) {
    if (url && url.indexOf('//') === 0) return (ishttp ? 'http:' : 'https:') + url;
    return url;
}

export function lookImage(url, urls, ishttp) {
    url = addHttps(url, ishttp);
    urls = urls || [url];
    if (window.wx) {
        window.wx.previewImage({
            current: url,
            urls
        });
    }
}

export function getFileSizeText(size) {
    if (size > 0) {
        if (size % (1024 * 1024) === 0) return size / (1024 * 1024) + 'M';
        else if (size % 1024 === 0) return size / 1024 + 'K';
        else {
            if (size > 1024 * 1024) return (size / (1024 * 1024)).toFixed(2) + 'M';
            return (size / 1024).toFixed(2) + 'M';
        }
    }
    return size;
}

export function enlarge(value, scale) {
    const f = parseFloat(value);
    if (isNaN(f)) return 0;
    if (f === 0) return f;

    scale = (scale || 2);
    scale = Math.pow(10, scale);
    return Math.round(f * scale);
}

export function getQrCode(url) {
    QrCode.typeNumber = 10;
    return QrCode.toDataURL(url, 4);
}

export function getQrCodeText(text) {
    return QrCode.toDataURL(text, 4);
}